package in.co.codedoc.struts;

import in.co.codedoc.json.JSONArrayValue;
import in.co.codedoc.json.JSONObjectValue;
import in.co.codedoc.json.JSONStringValue;
import in.co.codedoc.json.JSONValue;
import in.co.codedoc.rpc.RPCUtil;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class ServiceInvokingAction
	extends ActionSupport
{
	@SuppressWarnings("unchecked")
	@Override
	public String execute()
	{
		HttpServletRequest request = ServletActionContext.getRequest();

		String returnCode = Action.SUCCESS;
		
		String actionName = request.getParameter("msActionName");
		
		if(actionName == null)
		{
			actionName = ActionContext.getContext().getName();
		}
		else
		{
			returnCode = actionName;
		}
		
		JSONObjectValue arguments = new JSONObjectValue();
		
		Enumeration<String> parameters = request.getParameterNames();
		
		while(parameters.hasMoreElements())
		{
			String parameter = parameters.nextElement();
			
			String[] values = request.getParameterValues(parameter);
			
			if(values.length == 1)
			{
				arguments.SetProperty(parameter, new JSONStringValue(values[0]));
			}
			else
			{
				JSONArrayValue arrayValue = new JSONArrayValue();
				for(String value:values)
				{
					arrayValue.Add(new JSONStringValue(value));
				}
				arguments.SetProperty(parameter, arrayValue);
			}
		}
		
		try
		{
			returnValue = RPCUtil.ExecuteService(actionName, arguments);
			return returnCode;
		}
		catch(Throwable th)
		{
			throwable = th;
			return (th.getMessage().indexOf("No authorization") >= 0) ? Action.LOGIN : Action.ERROR;
		}
	}
	
	public JSONValue getReturnValue()
	{
		return returnValue;
	}
	
	public JSONValue getReturnValueId()
	{
		return (returnValue != null)
		&& (returnValue instanceof JSONObjectValue)
		&& ((JSONObjectValue)returnValue).HasProperty("id")
		?
			((JSONObjectValue)returnValue).GetProperty("id")
		:
			null
			;
	}
	
	public Throwable getThrowable()
	{
		return throwable;
	}
	
	private JSONValue returnValue;
	private Throwable throwable;
}
